package md.sv.dbu.receiver;

import md.sv.dbu.config.jaxb.ReceiveMQType;
import md.sv.dbu.mq.MQReceiver;

/**
 * @author MG
 */
public class MQMessageReceiver implements MessageReceiver<ReceiveMQType> {


    @Override
    public void receiveMessages(ReceiveMQType mqConfig, int maxMessageRead, ReceiverCallback receiverCallback) {
        MQReceiver rcv = new MQReceiver(mqConfig.getManager(), mqConfig.getQueueFrom(), mqConfig.getQueueError());

        if (!rcv.open()) {
            return;
        }

        while (maxMessageRead > 0) {
            maxMessageRead--;
            try {
                String message = rcv.getMessageFromQueue();
                if (message == null) {
                    break;
                }
                //TODO: save to file in case of error
                //TODO: check DOC_ED_NO in file name
                message = message.substring(message.indexOf("<?"), message.lastIndexOf(">") + 1);
                message = message.replace("&quot;", "\"");

                boolean result = receiverCallback.onReceive(message);

                if (result) {
                    if (mqConfig.isRemoveFromQueue()) {
                        rcv.removeCurrentMessageFromQueue();
                    } else {
                        rcv.moveMessageToErrorQueue();
                    }
                } else {
                    if (mqConfig.isRemoveFromQueueOnError()) {
                        rcv.moveMessageToErrorQueue();
                    }
                }

            } finally {
                rcv.removeCurrentMessageFromQueue();
            }

        }

        rcv.close();
    }
}
